/*
 */
package org.hook.showcase.concurrent.atomic;

import static org.testng.Assert.assertEquals;

import java.util.concurrent.atomic.AtomicInteger;

import org.testng.annotations.Test;

/**
 * @author suwuqiang 2011-12-12
 */
public class AtomicIntegerTest {
	private final AtomicInteger value = new AtomicInteger(10);

	@Test
	public void testAll() {
		assertEquals(value.compareAndSet(1, 2), false); // 10
		assertEquals(value.get(), 10);
		assertEquals(value.compareAndSet(10, 3), true); // 3
		assertEquals(value.get(), 3);
		value.set(0);
		assertEquals(value.incrementAndGet(), 1); // 1
		assertEquals(value.getAndAdd(2), 1); // 3(1+2)，返回旧值
		assertEquals(value.getAndSet(5), 3); // 5，返回旧值
		assertEquals(value.get(), 5);
		final int threadSize = 10;
		Thread[] ts = new Thread[threadSize];
		for (int i = 0; i < threadSize; i++) {
			ts[i] = new Thread() {
				public void run() {
					value.incrementAndGet();
				}
			};
		}
		for (Thread t : ts) {
			t.start();
		}
		for (Thread t : ts) {
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		assertEquals(value.get(), 5 + threadSize); // 15
	}
}
